﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common;
using BLL;
using Model;
using System.Diagnostics;
using System.Text;

namespace MDP.WebOpenPortal.Controllers
{
    public class PublicController : Controller
    {
        #region 常量

        public const string SQLSERVER_FRAMAT = "Server={0};database={1};uid={2};pwd={3};";
        public const string ORACLE_FRAMAT = @"Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = {0})(PORT = {4}))(CONNECT_DATA =(SID = {5})(SERVER = DEDICATED)(SERVICE_NAME = {1})));User Id={2};Password={3};";
        public const string ACCESS_FRAMAT = "{0}|{1}|{2}";
        public const string MYSQL_FRAMAT = "Server={0};port={4};database={1};user id={2};password={3};";
        public const string EXCEL_FRAMAT = ACCESS_FRAMAT;
        public const string TXT_FRAMAT = ACCESS_FRAMAT;

        #endregion

        public ActionResult AddDB()
        {
            return View();
        }
        public ActionResult AddCallBack()
        {
            return View();
        }
        public ActionResult AddWDC()
        {
            return View();
        }

        public ActionResult TestConeciton(string dbType, string connectionString)
        {
            Dictionary<string, string> query = connectionString.FromJSon<Dictionary<string, string>>();

            string strCon = "";
            string dataSource = query["Host"];
            string database = query["Server"];
            string userID = query["User"];
            string password = query["Pass"];
            string port = query["Part"];
            string sid = query["SID"];
            string fileUrl = query["FileUrl"];
            string fileUser = query["FileUser"];
            string filePass = query["FilePass"];
            LoginInfo loginInfos = new LoginInfo();
            SysPublicBLL bll = new SysPublicBLL(loginInfos);
            string conn = "";
            switch (dbType)
            {
                case "1":
                    strCon = string.Format(SQLSERVER_FRAMAT, dataSource, database, userID, password, port, sid);
                    conn = bll.TestConeciton(int.Parse(dbType), strCon);
                    break;
                case "2":
                    strCon = string.Format(ORACLE_FRAMAT, dataSource, database, userID, password, port, sid);
                    if (dataSource.IndexOf("|") > -1)
                    {
                        List<string> hostArr = dataSource.Split('|').ToList();
                        List<string> portArr = port.Split('|').ToList();
                        StringBuilder ora = new StringBuilder();
                        ora.Append("Data Source =(DESCRIPTION =");
                        for (int i = 0; i < hostArr.Count; i++)
                        {
                            ora.Append(string.Format(" (ADDRESS = (PROTOCOL = TCP)(HOST = {0})(PORT = {1}))", hostArr[i], portArr[i]));
                        }
                        ora.Append(string.Format("(CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = {0})));User Id={1};Password={2};", database, userID, password));
                        strCon = ora.ToString();
                    }
                    conn = bll.TestConeciton(int.Parse(dbType), strCon);
                    break;
                case "4":
                case "8":
                    strCon = string.Format(MYSQL_FRAMAT, dataSource, database, userID, password, port, sid);
                    conn = bll.TestConeciton(int.Parse(dbType), strCon);
                    break;
                default:
                    strCon = string.Format(ACCESS_FRAMAT, fileUrl, fileUser, filePass);
                    if (fileUrl.StartsWith("ftp", StringComparison.CurrentCultureIgnoreCase))
                    {
                        List<string> a = new List<string>();
                        conn = SysPublicBLL.readerFtp(fileUrl, fileUser, filePass, out a);
                    }
                    else
                        conn = SetFileShared(strCon, fileUser, filePass);
                    break;
            }
            return Json(conn);
        }


        private string SetFileShared(string f, string userName, string passWord)
        {
            string dosLine = string.Format("net use {0} \"{2}\" /user:\"{1}\" /PERSISTENT:YES", f.Substring(0, f.LastIndexOf("\\")), userName, passWord);
            return RunDos(dosLine);
        }
        private string RunDos(string dosLine)
        {
            string msg = "";
            Process proc = new Process();

            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    msg = "1";
                }
                else
                    msg = errormsg;

            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return msg;
        }

    }
}
